package com.dzt.cloudreader.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.dzt.cloudreader.R;
import com.dzt.cloudreader.adapter.GalleryPagerAdapter;
import com.dzt.cloudreader.adapter.LocalGalleryAdapter;
import com.dzt.cloudreader.base.FrameActivity;
import com.dzt.cloudreader.utils.JToastKit;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;

public class GalleryActivity extends FrameActivity
		implements ViewPager.OnPageChangeListener {

	@BindView(R.id.viewpager)
	ViewPager viewPager;
	@BindView(R.id.very_image_viewpager_text)
	TextView tvText;
	@BindView(R.id.tv_save_big_image)
	TextView tvSave;
	private GalleryPagerAdapter adapter;
	private ArrayList<String> imageuri;
	//传过来当前选择图片的数量
	private int code;
	//用于判断是头像还是文章图片 1:头像 2：文章大图
	private int selet;
	// 当前页数
	private int page;
	//本应用图片的id
	private int imageId;
	//是否是本应用中的图片
	private boolean isApp;
	//用于判断是否是加载本地图片
	private boolean isLocal;

	@Override
	protected int getLayoutId() {
		return R.layout.activity_gallery;
	}

	@Override
	protected void initParams() {
		Bundle bundle = getIntent().getExtras();
		code = bundle.getInt("code");
		selet = bundle.getInt("selet");
		isLocal = bundle.getBoolean("isLocal", false);
		imageuri = bundle.getStringArrayList("imageuri");
		/**是否是本应用中的图片*/
		isApp = bundle.getBoolean("isApp", false);
		/**本应用图片的id*/
		imageId = bundle.getInt("id", 0);

		/**
		 * 给viewpager设置适配器
		 */
		if (isApp) {
			LocalGalleryAdapter localGalleryAdapter = new LocalGalleryAdapter(context, imageId);
			viewPager.setAdapter(localGalleryAdapter);
			viewPager.setEnabled(false);
		} else {
			adapter = new GalleryPagerAdapter(context, imageuri);
			viewPager.setAdapter(adapter);
			viewPager.setCurrentItem(code);
			page = code;
			viewPager.setOnPageChangeListener(this);
			viewPager.setEnabled(false);
			// 设定当前的页数和总页数
			if (selet == 2) {
				tvText.setText((code + 1) + " / " + imageuri.size());
			}
		}

		tvSave.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				JToastKit.getInstance().showMessage("开始下载图片");
				if (isApp) {// 本地图片
					Bitmap bitmap = BitmapFactory.decodeResource(getResources(), imageId);
					if (bitmap != null) {
						saveImageToGallery(GalleryActivity.this, bitmap);
						JToastKit.getInstance().showMessage("保存成功");
					}

				} else {// 网络图片
					final BitmapFactory.Options bmOptions = new BitmapFactory.Options();
					new Thread(new Runnable() {
						@Override
						public void run() {
							// 子线程获得图片路径
							final String imagePath = getImagePath(imageuri.get(page));
							// 主线程更新
							GalleryActivity.this.runOnUiThread(new Runnable() {
								@Override
								public void run() {
									if (imagePath != null) {
										Bitmap bitmap = BitmapFactory.decodeFile(imagePath, bmOptions);
										if (bitmap != null) {
											saveImageToGallery(GalleryActivity.this, bitmap);
											JToastKit.getInstance().showMessage("已保存至" + Environment.getExternalStorageDirectory().getAbsolutePath() + "/云阅相册");
										}
									}
								}
							});
						}
					}).start();
				}
			}
		});
	}

	/**
	 * Glide 获得图片缓存路径
	 */
	private String getImagePath(String imgUrl) {
		String path = null;
		FutureTarget<File> future = Glide.with(GalleryActivity.this)
				.load(imgUrl)
				.downloadOnly(500, 500);
		try {
			File cacheFile = future.get();
			path = cacheFile.getAbsolutePath();
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
		return path;
	}

	/**
	 * 保存图片至相册
	 */
	public static void saveImageToGallery(Context context, Bitmap bmp) {
		// 首先保存图片
		File appDir = new File(Environment.getExternalStorageDirectory(), "云阅相册");
		if (!appDir.exists()) {
			appDir.mkdir();
		}
		String fileName = System.currentTimeMillis() + ".jpg";
		File file = new File(appDir, fileName);
		try {
			FileOutputStream fos = new FileOutputStream(file);
			bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
			fos.flush();
			fos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 其次把文件插入到系统图库
		try {
			MediaStore.Images.Media.insertImage(context.getContentResolver(),
					file.getAbsolutePath(), fileName, null);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		// 最后通知图库更新
		context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsoluteFile())));
	}

	@Override
	public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

	}

	@Override
	public void onPageSelected(int position) {
		// 每当页数发生改变时重新设定一遍当前的页数和总页数
		tvText.setText((position + 1) + " / " + imageuri.size());
		page = position;
	}

	@Override
	public void onPageScrollStateChanged(int state) {

	}
}
